<template>
  <div class="app-container">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>基本信息</span>
        </div>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="报修人" prop="reporterName">
              <el-input 
                v-model="form.reporterName" 
                placeholder="请选择报修人" 
                readonly
                @click.native="openUserSelectDialog"
              >
                <el-button slot="append" icon="el-icon-user" @click.stop="openUserSelectDialog">选择</el-button>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属部门" prop="departmentName">
              <el-input 
                v-model="form.departmentName" 
                placeholder="选择报修人后自动填充"
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="手机号码" prop="hiddenReporterPhone">
              <el-input 
                v-model="form.hiddenReporterPhone" 
                placeholder="选择报修人后自动填充"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="故障时间" prop="faultTime">
              <el-date-picker
                v-model="form.faultTime"
                type="datetime"
                placeholder="请选择故障时间"
                value-format="yyyy-MM-dd HH:mm:ss"
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="优先级" prop="priority">
              <el-select v-model="form.priority" placeholder="请选择优先级" style="width: 100%;">
                <el-option
                  v-for="dict in priorityOptions"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备" prop="equipmentId">
              <el-select
                v-model="form.equipmentId"
                filterable
                placeholder="请选择设备"
                style="width: 100%;"
                @change="handleEquipmentChange"
              >
                <el-option
                  v-for="item in equipmentOptions"
                  :key="item.equipmentId"
                  :label="item.equipmentName + ' (' + item.equipmentCode + ')'"
                  :value="item.equipmentId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <el-card class="box-card" style="margin-top: 20px;">
        <div slot="header" class="clearfix">
          <span>故障信息</span>
        </div>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="故障描述" prop="faultDesc">
              <el-input
                v-model="form.faultDesc"
                type="textarea"
                placeholder="请输入故障描述"
                :rows="4"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="故障图片">
              <el-upload
                class="avatar-uploader"
                action="#"
                :show-file-list="false"
                :on-success="handleUploadSuccess"
                :before-upload="beforeUpload"
                :http-request="uploadFaultImage">
                <img v-if="form.imageUrl" :src="form.imageUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="form.remark"
                type="textarea"
                placeholder="请输入备注"
                :rows="2"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <div class="bottom-control">
        <el-button type="primary" @click="submitForm">保 存</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-form>

    <!-- 用户选择对话框 -->
    <el-dialog title="选择报修人" :visible.sync="userSelectVisible" width="800px" append-to-body>
      <!-- 搜索区域 -->
      <el-form :model="userQueryParams" ref="userQueryForm" :inline="true">
        <el-form-item label="用户名称" prop="userName">
          <el-input
            v-model="userQueryParams.userName"
            placeholder="请输入用户名称"
            clearable
            size="small"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item label="手机号码" prop="phonenumber">
          <el-input
            v-model="userQueryParams.phonenumber"
            placeholder="请输入手机号码"
            clearable
            size="small"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="small" @click="handleUserQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="small" @click="handleUserReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 用户列表 -->
      <el-table
        v-loading="userLoading"
        :data="userList"
        @row-click="selectUser"
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column type="index" label="序号" width="50" align="center" />
        <el-table-column prop="userName" label="用户名称" min-width="100" show-overflow-tooltip />
        <el-table-column prop="nickName" label="用户昵称" min-width="100" show-overflow-tooltip />
        <el-table-column prop="phonenumber" label="手机号码" min-width="120" show-overflow-tooltip />
        <el-table-column prop="dept.deptName" label="部门" min-width="120" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>{{ scope.row.dept ? scope.row.dept.deptName : '' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="80">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click.stop="selectUser(scope.row)">选择</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="userTotal > 0"
        :total="userTotal"
        :page.sync="userQueryParams.pageNum"
        :limit.sync="userQueryParams.pageSize"
        @pagination="loadUserList"
      />
    </el-dialog>

    <!-- 图片预览 -->
    <el-dialog :visible.sync="dialogVisible" append-to-body>
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import { addRepairApplication, getAvailableEquipments } from "@/api/sb/repairApplication";
import { uploadFaultImage } from "@/api/common/upload";
import { listUser } from "@/api/system/user";

export default {
  name: "RepairApplicationAdd",
  data() {
    return {
      // 表单参数
      form: {
        reporterName: "",
        equipmentId: null,
        equipmentName: "",
        equipmentCode: "",
        faultDesc: "",
        faultTime: "",
        priority: "1",
        imageUrl: "", // 单张图片URL
        remark: "",
        userId: null, // 用户ID
        departmentName: "", // 部门名称
        departmentId: null, // 部门ID
        reporterPhone: "", // 添加报修人手机号字段
        hiddenReporterPhone: "" // 隐藏字段，用于显示手机号码
      },
      // 表单校验
      rules: {
        reporterName: [
          { required: true, message: "报修人不能为空", trigger: "blur" }
        ],
        equipmentId: [
          { required: true, message: "请选择设备", trigger: "change" }
        ],
        faultDesc: [
          { required: true, message: "故障描述不能为空", trigger: "blur" }
        ],
        faultTime: [
          { required: true, message: "故障时间不能为空", trigger: "change" }
        ],
        priority: [
          { required: true, message: "请选择优先级", trigger: "change" }
        ]
      },
      // 优先级选项
      priorityOptions: [
        { value: "1", label: "普通" },
        { value: "2", label: "紧急" },
        { value: "3", label: "非常紧急" }
      ],
      // 设备选项
      equipmentOptions: [],
      // 图片预览URL
      dialogImageUrl: "",
      // 预览窗口是否可见
      dialogVisible: false,
      // 用户选择相关
      userSelectVisible: false,
      userLoading: false,
      userList: [],
      userTotal: 0,
      userQueryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined
      }
    };
  },
  created() {
    this.getEquipmentOptions();
  },
  methods: {
    // 获取设备选项
    getEquipmentOptions() {
      getAvailableEquipments().then(response => {
        if (response.code === 200 && response.rows) {
          this.equipmentOptions = response.rows;
        } else {
          this.$message.error("获取设备列表失败");
          console.error("获取设备列表错误:", response);
        }
      }).catch(error => {
        this.$message.error("获取设备列表失败");
        console.error("获取设备列表错误:", error);
      });
    },
    
    // 设备选择变化
    handleEquipmentChange(equipmentId) {
      // 查找选择的设备
      const selectedEquipment = this.equipmentOptions.find(item => item.equipmentId === equipmentId);
      if (selectedEquipment) {
        // 设置设备名称和编码
        this.form.equipmentName = selectedEquipment.equipmentName;
        this.form.equipmentCode = selectedEquipment.equipmentCode;
      }
    },
    // 提交表单
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 显示加载状态
          this.$modal.loading("正在提交数据，请稍候...");
          
          // 创建一个新对象，将前端字段名映射到后端字段名
          const submitData = {
            // 后端字段名: 前端字段值
            reportPerson: this.form.reporterName,
            reportPhone: this.form.reporterPhone, // 使用从用户信息中获取的手机号
            equipmentId: this.form.equipmentId,
            equipmentCode: this.form.equipmentCode,
            equipmentName: this.form.equipmentName,
            faultDescription: this.form.faultDesc,
            faultImages: this.form.imageUrl ? JSON.stringify([this.form.imageUrl]) : "[]", // 将单张图片URL转为JSON字符串
            faultTime: this.form.faultTime,
            priority: this.form.priority,
            remark: this.form.remark,
            userId: this.form.userId, // 添加用户ID
            departmentId: this.form.departmentId, // 添加部门ID
            departmentName: this.form.departmentName // 添加部门名称
          };
          
          console.log("提交数据:", submitData);
          console.log("报修人手机号:", submitData.reportPhone); // 添加日志输出，确认手机号码
          
          addRepairApplication(submitData).then(response => {
            this.$modal.closeLoading();
            if (response.code === 200) {
              this.$modal.msgSuccess("新增成功");
              // 使用replace避免在历史记录中留下新增页面
              this.$router.replace({ path: "/sb/repair-application" });
              // 通知父页面刷新列表
              this.$emit('refresh');
            } else {
              this.$modal.msgError(response.msg || "新增失败");
            }
          }).catch(error => {
            this.$modal.closeLoading();
            console.error("添加报修单错误:", error);
            let errorMsg = error.response && error.response.data ? error.response.data.msg : "新增失败";
            this.$modal.msgError(errorMsg || "提交数据失败，请稍后重试");
          });
        }
      });
    },
    // 取消按钮
    cancel() {
      // 使用replace避免在历史记录中留下新增页面
      this.$router.replace({ path: "/sb/repair-application" });
      // 通知父页面刷新列表
      this.$emit('refresh');
    },
    
    // 图片预览
    handlePreview(file) {
      this.dialogImageUrl = file.url || URL.createObjectURL(file.raw);
      this.dialogVisible = true;
    },
    
    // 上传前校验
    beforeUpload(file) {
      const isImage = file.type.indexOf('image/') === 0;
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isImage) {
        this.$message.error('上传文件只能是图片格式!');
        return false;
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
        return false;
      }
      return true;
    },
    
    // 上传故障图片
    uploadFaultImage(options) {
      const { file, onSuccess, onError } = options;
      const self = this; // 保存Vue实例的引用
      
      // 显示上传中提示
      this.$message.info('图片上传中...');
      
      console.log('准备上传故障图片，参数名:', 'avatarfile');
      console.log('文件类型:', file.type);
      console.log('文件大小:', file.size);
      
      // 使用原生XHR上传文件，避开axios的默认处理
      const xhr = new XMLHttpRequest();
      const formData = new FormData();
      formData.append('avatarfile', file);
      
      // 获取token
      const token = this.$store.getters.token;
      
      xhr.open('POST', process.env.VUE_APP_BASE_API + '/ldzl-sb/sb/upload/fault-image', true);
      xhr.setRequestHeader('Authorization', 'Bearer ' + token);
      
      xhr.onload = function() {
        if (xhr.status === 200) {
          try {
            const res = JSON.parse(xhr.responseText);
            console.log('故障图片上传响应:', res);
            let imageUrl = '';
            if (res.data && res.data.url) {
              imageUrl = res.data.url;
            } else if (res.url) {
              imageUrl = res.url;
            } else if (res.imgUrl) {
              imageUrl = res.imgUrl;
            } else if (res.data && typeof res.data === 'string') {
              imageUrl = res.data;
            } else if (res.data) {
              const possibleFields = ['url', 'imgUrl', 'imageUrl', 'path', 'filePath', 'fileName'];
              for (const field of possibleFields) {
                if (res.data[field]) {
                  imageUrl = res.data[field];
                  break;
                }
              }
            }
            if (imageUrl) {
              if (imageUrl && !imageUrl.startsWith('http') && !imageUrl.startsWith('/')) {
                imageUrl = process.env.VUE_APP_BASE_API + imageUrl;
              }
              console.log('设置故障图片URL:', imageUrl);
              
              // 设置表单中的图片URL
              self.form.imageUrl = imageUrl;
              
              // 显示成功消息
              self.$message.success('故障图片上传成功');
              
              onSuccess(res);
            } else {
              console.error('无法从响应中获取故障图片URL:', res);
              onError(new Error('无法获取图片URL'));
            }
          } catch (e) {
            console.error('解析故障图片响应失败:', e);
            onError(e);
          }
        } else {
          console.error('故障图片上传请求失败:', xhr.status);
          onError(new Error('上传失败，状态码: ' + xhr.status));
        }
      };
      
      xhr.onerror = function() {
        console.error('故障图片上传网络错误');
        onError(new Error('网络错误'));
      };
      
      xhr.upload.onprogress = function(e) {
        if (e.lengthComputable) {
          const percentComplete = (e.loaded / e.total) * 100;
          console.log('故障图片上传进度:', percentComplete + '%');
        }
      };
      
      xhr.send(formData);
    },
    
    // 上传成功回调
    handleUploadSuccess(res, file) {
      console.log("上传成功", res, file);
    },

    // 打开用户选择对话框
    openUserSelectDialog() {
      this.userSelectVisible = true;
      this.loadUserList();
    },

    // 加载用户列表
    loadUserList() {
      this.userLoading = true;
      listUser(this.userQueryParams).then(response => {
        this.userLoading = false;
        if (response.code === 200) {
          this.userList = response.rows;
          this.userTotal = response.total;
        } else {
          this.userList = [];
          this.userTotal = 0;
          this.$message.error("获取用户列表失败: " + (response.msg || "未知错误"));
        }
      }).catch(error => {
        this.userLoading = false;
        console.error("获取用户列表错误:", error);
        this.$message.error("获取用户列表失败");
      });
    },

    // 用户搜索
    handleUserQuery() {
      this.userQueryParams.pageNum = 1;
      this.loadUserList();
    },

    // 用户重置查询
    handleUserReset() {
      this.$refs["userQueryForm"].resetFields();
      this.userQueryParams = {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined
      };
      this.loadUserList();
    },

    // 选择用户
    selectUser(row) {
      this.form.reporterName = row.nickName; // 使用用户昵称作为报修人
      this.form.userId = row.userId; // 保存用户ID
      this.form.departmentName = row.dept ? row.dept.deptName : '';
      this.form.departmentId = row.dept ? row.dept.deptId : null;
      this.form.reporterPhone = row.phonenumber || ''; // 保存用户手机号
      this.form.hiddenReporterPhone = row.phonenumber || ''; // 设置隐藏字段
      this.userSelectVisible = false;
      this.$message.success("已选择报修人：" + row.nickName);
    }
  }
};
</script>

<style scoped>
.bottom-control {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  height: 60px;
  line-height: 60px;
  background: #fff;
  box-shadow: 0 -3px 5px rgba(0, 0, 0, 0.1);
  text-align: center;
  z-index: 99;
  padding: 0 20px;
}
.app-container {
  padding-bottom: 60px;
}
.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}

/* 图片上传样式 */
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 128px;
  height: 128px;
  line-height: 128px;
  text-align: center;
}
.avatar {
  width: 128px;
  height: 128px;
  display: block;
}
</style> 